"use client";
import { GameListRep, GameRequest } from "@/api/home";
import { userInfoApi } from "@/api/login";
import {
    UserInfoRep,
    UserVipInfo,
    Wallet,
    cleanBounsApi,
    getUserMoneyApi,
    getUserTransferApi,
} from "@/api/user";
import {
    BalanceContent,
    BonusContent,
    FreeContent,
    ReplayContent,
} from "@/components/ModalPopup/WalletDescribeModal";
import TipsModal, { ModalProps } from "@/components/TipsModal";
import useGame from "@/hooks/useGame";
import { Link, useRouter } from "@/i18n/routing";
import { useWalletStore } from "@/stores/useWalletStore";
import { WalletEnum } from "@/types";
import { vipImages } from "@/utils/constant";
import { flatPoint, percentage } from "@/utils/methods";
import { Badge, Button, Mask, ProgressBar, Toast } from "antd-mobile";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { Fragment, useEffect, useRef, useState } from "react";

type Props = {
    userInfo: UserInfoRep;
    userMoney: Wallet;
    userVip: UserVipInfo;
};
const VipCard = (props: { userVip: UserVipInfo }) => {
    const { userVip } = props;
    const t = useTranslations("ProfilePage");

    // Vip 图标
    const vipIconElement = vipImages.map((item, index) => {
        if (item.leve === userVip?.vip_level) {
            return (
                <Fragment key={index}>
                    <Image src={item.src} alt={"vip"} height={110} width={100} />
                    <span className={"icon-level"} style={{ color: item.color }}>
                        {item.leve}
                    </span>
                </Fragment>
            );
        }
    });

    if (!userVip) return null;
    return (
        <div className={"vip-card"}>
            <div className={"vip-card__icon"}>{vipIconElement}</div>
            <div className={"vip-card-process"}>
                {/*<div className={"process-top"}>{userVip.vip_exp}xp</div>*/}
                <div>
                    <ProgressBar
                        percent={percentage(userVip?.vip_exp, userVip?.vip_score_exp)}
                        style={{
                            "--fill-color": "#bd37e0",
                            "--track-color": "#65609b",
                            "--track-width": "0.0694rem",
                        }}
                    />
                </div>
                <div className={"process-bottom text-[#e581ff]"}>
                    <span>VIP{userVip?.vip_level}</span>
                    <span className={"process-bottom-desc"}>
                        {t("expTips", {
                            exp: flatPoint(userVip.vip_score_exp - userVip.vip_exp),
                        })}
                    </span>
                    <span>
                        VIP
                        {userVip.vip_next_level}
                    </span>
                </div>
            </div>
        </div>
    );
};

const WalletCard = (props: { userMoney: Wallet }) => {
    const { userMoney } = props;
    const t = useTranslations("ProfilePage");
    const tcdoe = useTranslations();

    const tipsRef = useRef<ModalProps>(null);
    const [tipsStatus, setTipsStatus] = useState<keyof typeof WalletEnum>("Bonus");

    const modalHandler = (key: keyof typeof WalletEnum) => {
        setTipsStatus(key);
        tipsRef.current?.onOpen();
    };

    // 未完成游戏
    const gameModelRef = useRef<ModalProps>(null);
    const game = useRef<(GameListRep & { mode: GameRequest["mode"] }) | null>(null);

    // 彩金、免费币、重玩币提现到钱包操作
    const handleAcquire = async (wallet_type: number, transfer: boolean) => {
        if (!transfer) return;

        // 先判断是否有未完成的游戏
        const { data }: any = await userInfoApi();

        // 如果有未完成游戏 彩金游戏-2、免费游戏-3、重玩游戏-4
        if (wallet_type === 2 && data.play_list && data.play_list.length > 0) {
            game.current = data.play_list[0];
            game.current!.mode = 1;
            gameModelRef.current?.onOpen();
            return;
        }

        if (wallet_type === 3 && data.free_game_list && data.free_game_list.length > 0) {
            game.current = data.free_game_list[0];
            gameModelRef.current?.onOpen();
            game.current!.mode = 2;
            return;
        }

        if (wallet_type === 4 && data.lose_game_list && data.lose_game_list.length > 0) {
            game.current = data.lose_game_list[0];
            game.current!.mode = 3;
            gameModelRef.current?.onOpen();
            return;
        }

        getUserTransferApi({ wallet_type })
            .then((res) => {
                if (res.code === 200) {
                    Toast.show(tcdoe("code.200"));
                    setTimeout(() => {
                        tipsRef.current?.onClose();
                    }, 1000);
                }
            })
            .catch((error) => {
                Toast.show(tcdoe(`code.${error.data.code}`));
            });
    };

    const { getGameUrl } = useGame();
    const goGame = () => {
        const current = game.current;
        getGameUrl(current!, { id: current?.id + "", mode: game.current?.mode! });
        tipsRef.current?.onClose();
        gameModelRef.current?.onClose();
    };

    return (
        <>
            <TipsModal
                className="walletModal"
                ref={tipsRef}
                title={
                    <div className={"flex items-center text-[#00f6ff]"}>
                        <i
                            className={"iconfont icon-liwuhuodong mr-[0.0694rem] text-[0.2778rem]"}
                        ></i>
                        {t("modalTitle")}
                    </div>
                }
            >
                {/*现金*/}
                {tipsStatus === WalletEnum.Balance ? <BalanceContent wallet={userMoney} /> : null}
                {/*  彩金*/}
                {tipsStatus === WalletEnum.Bonus ? (
                    <BonusContent wallet={userMoney} handleAcquire={handleAcquire} />
                ) : null}
                {/* 免费币 */}
                {tipsStatus === WalletEnum.Free ? (
                    <FreeContent wallet={userMoney} handleAcquire={handleAcquire} />
                ) : null}
                {/*  重玩币 */}
                {tipsStatus === WalletEnum.Replay ? (
                    <ReplayContent wallet={userMoney} handleAcquire={handleAcquire} />
                ) : null}
            </TipsModal>
            {/*   提现拦截 */}
            <TipsModal title={"Tips"} ref={gameModelRef}>
                <p className={"text-left text-[0.12rem] font-medium text-[#666]"}>
                    Existem jogos de bônus pendentes que não podem iniciar a retirada.
                </p>

                <div className={"mt-[0.0694rem] flex justify-center"}>
                    <Button
                        color={"primary"}
                        className={"mx-auto"}
                        style={{
                            "--background-color": "var(--primary-color)",
                            "--border-color": "var(--primary-color)",
                        }}
                        onClick={goGame}
                    >
                        para jogos
                    </Button>
                </div>
            </TipsModal>
            <div className="coin">
                <div className={"coin_right_wallet"}>
                    <div
                        className={"wallet_left_border"}
                        onClick={() => modalHandler(WalletEnum.Balance)}
                    >
                        <div className="wallet-right-icon">
                            <span className="coin_left__icon iconfont icon-qianbao3"></span>
                        </div>
                        <section>
                            <div className={"wallet_header"}>
                                <span>{t("balance")}</span>
                                {/* <Image
                                    className="wallet_header__icon"
                                    src="/img/a.png"
                                    alt="question"
                                    width={15}
                                    height={15}
                                /> */}
                                <div className="wallet-question">?</div>
                            </div>
                            <div className="num">
                                <span className="uppercase">brl </span>
                                <span>{userMoney.score || 0.0}</span>
                            </div>
                        </section>
                    </div>
                    <div
                        className={"wallet_right_content"}
                        onClick={() => modalHandler(WalletEnum.Bonus)}
                    >
                        <Badge
                            content={userMoney.is_point_transfer ? Badge.dot : null}
                            style={{ right: "10px" }}
                        >
                            <div className="wallet-right-icon">
                                <span className="coin_left__icon iconfont icon-qianbao3"></span>
                            </div>
                        </Badge>
                        <section>
                            <div className={"wallet_header"}>
                                {t("bonus")}
                                <div className="wallet-question">?</div>
                            </div>
                            <div className="num">
                                <span className="uppercase">brl </span>
                                <span>{userMoney.point || 0.0}</span>
                            </div>
                        </section>
                    </div>
                    <div
                        className={"wallet_left_border"}
                        onClick={() => modalHandler(WalletEnum.Free)}
                    >
                        <Badge
                            content={
                                userMoney.is_free_transfer &&
                                userMoney.free_score >= (userMoney?.free_transfer_min || 0)
                                    ? Badge.dot
                                    : null
                            }
                            style={{ right: "10px" }}
                        >
                            <div className="wallet-right-icon">
                                <span className="coin_left__icon iconfont icon-qianbao3"></span>
                            </div>
                        </Badge>
                        <section>
                            <div className={"wallet_header"}>
                                {t("free")}
                                <div className="wallet-question">?</div>
                            </div>
                            <div className="num">
                                <span className="uppercase">brl </span>
                                <span>{userMoney.free_score || 0.0}</span>
                            </div>
                        </section>
                    </div>
                    <div
                        className={"wallet_right_content"}
                        onClick={() => modalHandler(WalletEnum.Replay)}
                    >
                        <Badge
                            content={
                                userMoney.is_lose_transfer &&
                                userMoney.lose_score >= (userMoney?.lose_transfer_min || 0)
                                    ? Badge.dot
                                    : null
                            }
                            style={{ right: "10px" }}
                        >
                            <div className="wallet-right-icon">
                                <span className="coin_left__icon iconfont icon-qianbao3"></span>
                            </div>
                        </Badge>

                        <section>
                            <div className={"wallet_header"}>
                                {t("replay")}
                                <div className="wallet-question">?</div>
                            </div>
                            <div className="num">
                                <span className="uppercase">brl </span>
                                <span>{userMoney.lose_score || 0.0}</span>
                            </div>
                        </section>
                    </div>
                </div>
            </div>
        </>
    );
};
const NoBounsWarn = ({ visible, onClose, onConfirm }: any) => {
    const doClose = () => {
        if (typeof onClose === "function") onClose();
    };
    const doConfirm = () => {
        if (typeof onConfirm === "function") onConfirm();
    };

    return (
        <Mask visible={visible} onMaskClick={doClose}>
            <div className="absolute left-[50%] top-[40%] w-[80%] translate-x-[-50%]">
                <div className="relative rounded-[.1rem] border-[1px] border-[#e541ff] bg-gradient-to-b from-[#254cc5] to-[#4b179a] px-[.15rem] pb-[.15rem] pt-[0px] shadow-[0_-10px_15px_#7619b6_inset]">
                    <div className="h-[.5rem] text-center">
                        <img
                            src="/warn_top.png"
                            alt=""
                            className="relative -top-[.3rem] inline-block w-[.9rem]"
                        />
                    </div>
                    <div className="text-center text-[.12rem]">
                        A demanda atual de fluxo de retirada de bônus é excessiva，Se esvaziar o
                        bônus e retirar a demanda de água corrente？
                    </div>
                    <div className="mt-[.2rem] flex items-center justify-between px-[.1rem]">
                        <button
                            onClick={doConfirm}
                            className="mr-[.1rem] h-[.35rem] flex-1 rounded-[60px] border border-[#e746ff] bg-[#703dc3] text-[.14rem] font-bold text-[#00f6ff] shadow-[0_10px_5px_#8f42d2_inset]"
                        >
                            A certeza
                        </button>
                        <button
                            onClick={doClose}
                            className="h-[.35rem] flex-1 rounded-[60px] border border-[#46e3ff] bg-[#6c3bc1] text-[.14rem] font-bold text-[#00f6ff] shadow-[0_-10px_5px_#4d4ebf_inset]"
                        >
                            Cancelar
                        </button>
                    </div>
                    <i
                        className="iconfont icon-guanbi absolute right-[.1rem] top-[.1rem]"
                        onClick={doClose}
                    ></i>
                </div>
            </div>
        </Mask>
    );
};
export const ProfileHeader = (props: Props) => {
    const { userInfo, userVip } = props;
    const t = useTranslations("ProfilePage");

    const { wallet, setWallet } = useWalletStore((state) => ({
        wallet: state.wallet,
        setWallet: state.setWallet,
    }));
    const router = useRouter();
    const [isShowNoBounsWarn, setIsShowNoBounsWarn] = useState(false);
    const [isShowed, setIsShowed] = useState(false);
    useEffect(() => {
        const curMul = wallet.target_point_rollover / ((wallet?.score || 0) + (wallet.point || 0));
        const config = wallet.no_bonus_config;
        if (curMul >= (config || 0) && !isShowed) {
            setIsShowNoBounsWarn(true);
            setIsShowed(true);
        }
    }, [wallet]);

    const handler = () => {
        if (!!wallet.score) {
            router.push("/withdraw");
        } else {
            Toast.show("no money ");
        }
    };

    const doConfirm = async () => {
        Toast.show({
            icon: "loading",
            maskClickable: false,
        });
        setIsShowNoBounsWarn(false);
        const res = await cleanBounsApi(1);
        if (res?.code && [6001, 6002].includes(res?.data?.code)) {
            const str = t(`bouns${res?.data?.code}`);
            Toast.show({
                content: str,
                icon: "fail",
            });
        }
        Toast.show({
            content: t("success"),
            icon: "success",
        });
        const walletRes = await getUserMoneyApi();
        setWallet(walletRes?.data);
    };

    return (
        <>
            <div className={"userContent"}>
                <div className={"userInfo"}>
                    <div>
                        <div className={"bgImg"}>
                            <Image
                                src={"/img/avatar.png"}
                                className={"h-[100%] w-[100%]"}
                                alt={"avatar"}
                                width={120}
                                height={120}
                            />
                        </div>
                        <div>
                            <span>{t("Conta")}</span>
                            <span className="phone text-[#d3d1ff]">
                                {userInfo?.user_phone || ""}
                            </span>
                        </div>
                    </div>

                    <Link
                        className="goto iconfont icon-xiangzuo1 text-[#8883eb]"
                        href={`/changePassword`}
                    ></Link>
                </div>
                {/*vipcard*/}
                <VipCard userVip={userVip} />

                <WalletCard userMoney={wallet} />
            </div>

            <div className="link">
                <Link href={"/deposit"} className={"btn"}>
                    <span> {t("Depósito")}</span>
                </Link>
                <p className={"btn"} onClick={handler}>
                    <span>{t("Sacar")}</span>
                </p>
            </div>
            <NoBounsWarn
                visible={isShowNoBounsWarn} // 控制是否显示遮罩层，true 显示，false 不显示
                onClose={() => setIsShowNoBounsWarn(false)}
                onConfirm={doConfirm}
            ></NoBounsWarn>
        </>
    );
};
